package com.itheima.easy.controller;

import com.itheima.easy.base.AjaxResult;
import com.itheima.easy.config.AliOssConfig;
import com.itheima.easy.utils.AliOSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    AliOssConfig aliOssConfig;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public AjaxResult<String> upload(@RequestPart("file") MultipartFile file) throws Exception {//File是一个临时文件，当请求结束后自动删除

        //校验是否为图片文件
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        } catch (Exception e) {
            return AjaxResult.error();
        }

        //获得原始文件名
        String originalFilename = file.getOriginalFilename();
        //获得文件扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;

        String filePath = aliOssConfig.upload(file.getBytes(), fileName);

        return AjaxResult.success("",filePath);
    }

}
